package com.msh.automatic.android.control.ui.mqtt

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.msh.automatic.android.control.databinding.FragmentMqttBinding
import com.msh.automatic.android.control.ui.home.HomeViewModel
import com.msh.automatic.android.control.util.EventUtil
import kotlinx.coroutines.launch

class MqttFragment : Fragment() {

    private var _binding: FragmentMqttBinding? = null
    private lateinit var mqttViewModel: MqttViewModel

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMqttBinding.inflate(inflater, container, false)
        mqttViewModel = ViewModelProvider(this).get(MqttViewModel::class.java)
        _binding!!.viewModel = mqttViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        val root: View = binding.root
        Log.d("MqttFragment", "MqttMessage onCreateView")
        lifecycleScope.launch {
            Log.d("MqttFragment", "MqttMessage lifecycleScope")
            EventUtil.EventBus.events.collect { event ->
                when (event) {
                    is EventUtil.Message.MqttMessage -> {
                        Log.d("MqttFragment", "MqttMessage ${event.mqttTopic} ${event.mqttPayload}")
                        mqttViewModel.mqttMessage.value =
                        """
                        |topic: ${event.mqttTopic}
                        |payload: ${event.mqttPayload}
                        |
                        |${mqttViewModel.mqttMessage.value}
                        |
                        """.trimMargin()
                    }
                }
            }
        }
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}